package com.hnichr.ump.talent.library.provider.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnichr.ump.common.talent.library.entity.WorkIntention;
import com.hnichr.ump.common.talent.library.service.WorkIntentionService;
import com.hnichr.ump.talent.library.provider.SyncPolicyProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class WorkIntentionSyncPolicyProvider implements SyncPolicyProvider {
    private static final String KEY = "workIntentionList";

    @Autowired
    private WorkIntentionService workIntentionService;

    @Override
    public boolean support(JSONObject jsonObject) {
        return jsonObject.containsKey(KEY);
    }

    @Override
    @Transactional
    public void sync(String syncDate, JSONObject jsonObject) {
        JSONArray workIntentionList = jsonObject.getJSONArray(KEY);
        if(CollectionUtils.isEmpty(workIntentionList)){
            return;
        }
        for(Object workIntentionObject:workIntentionList){
            if(workIntentionObject instanceof JSONObject){
                JSONObject woJSONObject = (JSONObject) workIntentionObject;
                WorkIntention workIntention = new WorkIntention();
                workIntention.setId(woJSONObject.getString("id"));
                workIntention.setDelFlag(woJSONObject.getBoolean("delFlag"));
                workIntention.setUserId(woJSONObject.getString("userId"));
                if(woJSONObject.containsKey("createTime")){
                    workIntention.setOrginalCreateTime(new Date(woJSONObject.getLong("createTime")));
                }
                if(woJSONObject.containsKey("updateTime")){
                    workIntention.setOrginalUpdateTime(new Date(woJSONObject.getLong("updateTime")));
                }
                workIntention.setWorkType(woJSONObject.getString("workType"));
                workIntention.setWorkIndustry(woJSONObject.getString("workIndustry"));
                workIntention.setWorkNature(woJSONObject.getString("workNature"));
                workIntention.setMinMoney(woJSONObject.getInteger("minMoney"));
                workIntention.setMaxMoney(woJSONObject.getInteger("maxMoney"));
                workIntention.setCityId(woJSONObject.getString("cityId"));
                workIntention.setResumeId(woJSONObject.getString("resumeId"));
                workIntention.setSyncDate(syncDate);
                workIntentionService.merge(workIntention);
            }
        }
    }
}
